package com.javaclimb.filmbuy.controller;

import cn.hutool.core.io.FileUtil;
import com.github.pagehelper.PageInfo;
import com.javaclimb.filmbuy.common.Consts;
import com.javaclimb.filmbuy.common.Result;
import com.javaclimb.filmbuy.entity.NxSystemFileInfo;
import com.javaclimb.filmbuy.entity.TypeInfo;
import com.javaclimb.filmbuy.entity.UserInfo;
import com.javaclimb.filmbuy.exception.CustomException;
import com.javaclimb.filmbuy.service.NxSystemFileInfoService;
import com.javaclimb.filmbuy.service.TypeInfoService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 文件上传controller层
 */
@RestController
@RequestMapping(value = "/files")
public class NxSystemFileController {
    @Resource
    private NxSystemFileInfoService nxSystemFileInfoService;


    /**
     * 电影图片上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        //获取到当前上传的原始文件名
        String originalName =  file.getOriginalFilename();
        //新的文件名加个时间戳
        String fileName = FileUtil.mainName(originalName)+System.currentTimeMillis()+"."+FileUtil.extName(originalName);
        //文件上传
        FileUtil.writeBytes(file.getBytes(), Consts.BASE_PATH+fileName);
        //信息入库，获取文件主键id
        NxSystemFileInfo info = new NxSystemFileInfo();
        info.setOriginName(originalName);
        info.setFileName(fileName);
        NxSystemFileInfo addInfo = nxSystemFileInfoService.add(info);
        if(addInfo != null) {
            return Result.success(addInfo);
        }else{
            return Result.error("4001","上传失败");
        }
    }

    /*
     * 下载图片
     * */
    @GetMapping("/download/{id}")
    public void download(@PathVariable String id, HttpServletResponse response) throws IOException{
        if(id==null||id.equals("")||id.equals("null")){
            throw new CustomException("1001", "您未上传文件");
        }
        NxSystemFileInfo nxSystemFileInfo = nxSystemFileInfoService.findById(Long.parseLong(id));
        if(nxSystemFileInfo==null){
            throw new CustomException("1001", "未查询到该文件");
        }
        byte[] bytes = FileUtil.readBytes(Consts.BASE_PATH + nxSystemFileInfo.getFileName());
        response.reset();
        response.addHeader("Content-Disposition", "attchment;filename=" + URLEncoder.encode(nxSystemFileInfo.getOriginName(), "UTF-8"));
        response.addHeader("Content-Length", "" + bytes.length);
        response.setContentType("application/octet-stream");
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
        bufferedOutputStream.write(bytes);
        bufferedOutputStream.flush();
        bufferedOutputStream.close();
    }

}
